<template>
  <q-page padding>
    <q-card bordered flat>
      <q-splitter v-model="splitterModel" :limits="[30, 80]" :horizontal="$q.screen.lt.md">
        <template #before>
          <div class="q-pa-md">
            <div class="row justify-end">
              <q-btn outline dense icon="add" label="新增一级菜单" @click="handleAddMenu(0)" />
            </div>
            <q-tree
              bordered
              ref="treeRef"
              @update:selected="onSelected"
              default-expand-all
              :nodes="nodes"
              node-key="id"
              label-key="menu_name"
              selected-color="primary"
              v-model:selected="selected"
            >
              <template #default-header="{ node }">
                <div class="flex w-100% items-center justify-between">
                  <div>
                    <q-icon :name="node.icon" />
                    {{ node.menu_name }}
                  </div>
                  <div>
                    <q-btn
                      outline
                      dense
                      icon="add"
                      v-if="node.menu_type === '1'"
                      @click="handleAddMenu(node.id)"
                    />
                    <q-btn
                      outline
                      dense
                      class="ml-xs"
                      v-if="node.children && node.children.length === 0"
                      icon="delete"
                      @click="handleDelete(node.id)"
                    />
                  </div>
                </div>
              </template>
            </q-tree>
          </div>
        </template>
        <template #after>
          <div class="row">
            <q-form class="row q-pa-md q-gutter-x-md">
              <div class="w-100% flex justify-end q-gutter-x-md">
                <q-btn
                  outline
                  dense
                  :icon="isEdit ? 'edit' : 'remove_red_eye'"
                  @click="isEdit = !isEdit"
                  :label="isEdit ? '编辑' : '只读'"
                />
              </div>
              <q-select
                :readonly="isEdit"
                v-model="currentMenu.menu_type"
                :options="menuType"
                class="w-100%"
                map-options
                emit-value
                label="菜单类型"
              />
              <q-input
                :readonly="isEdit"
                v-model="currentMenu.menu_name"
                class="w-100%"
                label="菜单名称"
              />
              <q-input
                :readonly="isEdit"
                v-model="currentMenu.route_name"
                class="w-100%"
                label="路由名称"
              />
              <q-input
                :readonly="isEdit"
                v-model="currentMenu.route_path"
                class="w-100%"
                label="路由路径"
              />
              <q-input
                :readonly="isEdit"
                v-model="currentMenu.order"
                type="number"
                class="w-100%"
                label="排序"
              />
              <q-select
                :readonly="isEdit"
                v-model="currentMenu.status"
                :options="menuStatus"
                map-options
                emit-value
                class="w-100%"
                label="状态"
              />
              <q-input
                :readonly="isEdit"
                v-model="currentMenu.component"
                class="w-100%"
                label="组件"
              />
              <q-input :readonly="isEdit" v-model="currentMenu.icon" class="w-100%" label="图标">
                <template #append>
                  <q-icon :name="currentMenu.icon" />
                </template>
              </q-input>
              <!-- 菜单按钮 -->
              <q-list v-if="currentMenu.menu_type === '2'" bordered class="w-100% mt-30px q-py-md">
                <q-item-label header class="row justify-between">
                  <div>菜单按钮</div>
                  <q-btn
                    label="新增"
                    icon="add"
                    dense
                    outline
                    @click="handleAddButton"
                    :disabled="isEdit"
                  />
                </q-item-label>
                <q-separator v-if="currentMenu.menu_meta?.buttons?.length !== 0" inset />
                <q-item v-for="b in currentMenu.menu_meta?.buttons" :key="b.id" bordered>
                  <q-item-section>
                    <div class="flex flex-column justify-between">
                      <q-input
                        dense
                        class="w-50%"
                        :readonly="isEdit"
                        v-model="b.button_code"
                        label="编码"
                      />
                      <q-input
                        dense
                        class="w-50%"
                        :readonly="isEdit"
                        v-model="b.button_desc"
                        label="描述"
                      />
                    </div>
                  </q-item-section>
                  <q-item-section side>
                    <q-btn
                      icon="delete"
                      outline
                      dense
                      v-if="!isEdit"
                      @click="handleDeleteButton(b.id)"
                    />
                  </q-item-section>
                </q-item>
              </q-list>
            </q-form>
            <div class="q-pa-md">
              <q-btn
                dense
                outline
                icon="save"
                :disabled="isEdit"
                @click="handleUpdate"
                label="保存"
              />
            </div>
          </div>
        </template>
        <template v-slot:separator>
          <q-avatar color="primary" text-color="white" size="30px" icon="drag_indicator" />
        </template>
      </q-splitter>
    </q-card>
    <div>
      当前数据：
      <pre>{{ menuFormDataWithoutId }}</pre>
      <pre>{{ currentMenu }}</pre>
      <q-icon name="img:g1.gif" size="64px" />
    </div>
    <add-dialog-page v-model:dialog="dialog" v-model:pMenuId="pMenuId" @success="refresh" />
  </q-page>
</template>

<script setup lang="ts">
import { getMenuTree } from 'src/api/methods/menu'
import { useRequest } from 'alova/client'
import { deleteMenu, updateMenu } from 'src/api/methods/menu'
import type { MenuTree } from 'src/api/globals'
import { type QTree } from 'quasar'
import { computed, ref } from 'vue'
import { useDataReset } from 'src/hooks/useReset'
import addDialogPage from './addDialogPage.vue'
import { useQuasar } from 'quasar'
import { invalidateCache } from 'alova'
import { uid } from 'quasar'

defineOptions({
  name: 'MenuPage',
})

const $q = useQuasar()

// 是否编辑
const isEdit = ref(true)

const { data: nodes, send } = useRequest(getMenuTree(), { initialData: [] })

const menuFormData: MenuTree = {
  id: 0,
  menu_name: '',
  menu_type: '1',
  route_name: '',
  route_path: '',
  component: null,
  order: 0,
  parent_id: 0,
  icon: '',
  menu_meta: {
    href: '',
    multi_tab: false,
    hide_in_menu: false,
    redirect: '',
    constant: false,
    buttons: [],
  },
  status: '1',
  redirect: null,
  constant: false,
  children: [],
}

const { copy: initFormData } = useDataReset(menuFormData)

const selected = ref('销售管理')
const splitterModel = ref(50)
const treeRef = ref<QTree | null>(null)
const currentMenu = ref(initFormData)

const onSelected = (selected: string) => {
  if (selected) {
    const selectedNode = treeRef.value?.getNodeByKey(selected)
    if (selectedNode) {
      currentMenu.value = { ...selectedNode }
    }
  }
}

// 菜单类型
const menuType = [
  { label: '目录', value: '1' },
  { label: '菜单', value: '2' },
]

const menuStatus = [
  { label: '启用', value: '1' },
  { label: '禁用', value: '0' },
]

// 删除菜单
const handleDelete = (node: number) => {
  console.log(node)
  $q.dialog({
    title: '删除提示',
    message: '确认删除该菜单？',
    ok: '确认',
    cancel: '取消',
  }).onOk(() => {
    deleteMenu(node)
      .then(() => {
        refresh()
        $q.notify('删除成功')
      })
      .catch((err) => $q.notify({ message: err }))
  })
}

/**
 * 编辑菜单
 */

// 剔除id和children属性

const menuFormDataWithoutId = computed(() => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { id: _id, children: _children, ...menuFormDataWithoutId } = currentMenu.value
  return menuFormDataWithoutId
})

// 更新菜单
const handleUpdate = () => {
  console.log(menuFormDataWithoutId.value)
  updateMenu(currentMenu.value.id, menuFormDataWithoutId.value)
    .then(() => {
      refresh()
      isEdit.value = true
      $q.notify('更新成功')
    })
    .catch((err) => $q.notify({ message: err }))
}

const dialog = ref(false)
const pMenuId = ref(0)

// 添加一级菜单
const handleAddMenu = (pId: number) => {
  pMenuId.value = pId
  dialog.value = true
}

// 刷新
const refresh = () => {
  invalidateCache(getMenuTree()).catch((err) => alert('请求错误' + err))
  send().catch((err) => $q.notify('请求错误' + err))
}

// 新增菜单按钮
const handleAddButton = () => {
  currentMenu.value.menu_meta?.buttons?.push({
    id: uid(),
    button_code: '',
    button_desc: '',
  })
}
// 删除菜单按钮
const handleDeleteButton = (id: string) => {
  const index = currentMenu.value.menu_meta?.buttons?.findIndex((b) => b.id === id)
  if (index !== undefined && index !== -1) {
    currentMenu.value.menu_meta?.buttons?.splice(index, 1)
  }
}
</script>
